package com.huan.hystrix.configuration;

import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * hystrix 的配置文件
 *
 * @author huan.fu
 * @date 2018/8/10 - 14:26
 */
@Configuration
public class HystrixConfiguration {

	@Bean
	public ServletRegistrationBean hystrixMetricsStreamServlet() {
		return new ServletRegistrationBean(
				new HystrixMetricsStreamServlet(), "/hystrix.stream"
		);
	}

	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().stream()
				.forEach(converter -> {
					if (converter instanceof StringHttpMessageConverter) {
						((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
					}
				});
		return restTemplate;
	}

	@Bean
	public HystrixCommandAspect hystrixCommandAspect() {
		return new HystrixCommandAspect();
	}
}
